#include "stdafx.h"
#include <http_listener.h>
#include "azure_store.h"
#include "form_response.h"
#include "ttslib.h"

using namespace http;
using namespace http::listener;
using namespace std;

http_listener g_listener;

// Function to help find dynamically assigned port for our endpoint.
casablanca::string_t find_addr(const std::vector<casablanca::string_t> &configs)
{
    // The configuration data is a vector of [key1,value1,key2,value2,...,keyN,valueN] pairs.
    for(auto iter = configs.begin(); iter != configs.end(); ++iter)
    {
        if(*iter == U("EndPoint1"))
        {
            ++iter;
            return U("http://*:") + *iter;
        }
    }
    return U("http://*");
}

bool on_initialize(const std::vector<casablanca::string_t> &args, const std::vector<casablanca::string_t> &configs)
{
    g_listener = http_listener::create(find_addr(configs));

    // GET
    g_listener.support(methods::GET, [](http_request message)
    {
        if (message.relative_uri().path().to_string() == L"/")
		{
			form_response response;
			message.reply(response);
		}
    });

    // POST
    g_listener.support(methods::POST, [](http_request message)
    {
		if (message.relative_uri().path().to_string() == L"/")
		{
			auto request_data = message.extract_vector().get();
			casablanca::string_t body(request_data.begin(), request_data.end());

			auto map = http::uri::split_query_and_decode(http::uri::encoded_string(body));

			// TODO: QUESTION - is there a better way to get form data?
			auto value = general_utilities::html_decode(map.at(L"text"));

			// TODO: QUESTION - need to find a way to CoInitialize and CoUninitialize more efficiently?
			auto hr = ::CoInitialize(NULL);

			auto local_spoken_file = general_utilities::get_unique_filename(L"media\\", L".wav");

			if (SUCCEEDED(hr))
			{
				hr = tts_engine::speak(value.c_str(), local_spoken_file.c_str());
			}

			CoUninitialize();

#ifdef UPLOAD_TO_AZURE
			azure_blob_store blob_store(
				L"techedaudemo", 
				L"jbwiAcKFZmKU8vtjkQNMrWP80aUf3YAoXWmeqrIu66eEH119Eb5F7U1KQZVfOe2mfLhTOH06PTEh/rjX0FzGGw==", 
				L"http://techedaudemo.blob.core.windows.net",
				L"audio");
			auto saved_url = blob_store.save_file_to_blob(local_spoken_file.c_str());

			form_response response(saved_url);
#else
			form_response response(L"http://localhost:8182" + local_spoken_file);
#endif
			message.reply(response);
		}
    });

    return g_listener.open() == 0;
}

bool on_shutdown()
{
    // TODO: Implement on_shutdown. This will be called by Casablanca when SpeechService.dll is unloaded.
    return g_listener.close() == 0;
}

